package com.moxi.mogublog.admin.security;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashSet;
import java.util.Set;
import java.util.regex.Pattern;

public class IpAccessFilter extends OncePerRequestFilter {


    @Value("${allowed.ips}")
    private String[] allowedIps;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
            throws ServletException, IOException {
        String remoteIp = request.getRemoteAddr();
        String requestUri = request.getRequestURI();

        if (requestUri.startsWith("/webService/")) {
            System.out.println("Request IP: " + remoteIp);
            if (matchesAnyPattern(remoteIp)) {
                System.out.println("has Pass");
                chain.doFilter(request, response);
            } else {
                System.out.println("Access denied for IP: " + remoteIp);
                response.sendError(HttpServletResponse.SC_FORBIDDEN, "Access Denied");
                return;
            }
        } else {
            chain.doFilter(request, response);
        }
    }

    private Pattern convertToPattern(String ip) {
        // Convert IP address with wildcards to regex pattern
        String regex = ip.replace(".", "\\.")
                .replace("*", ".*");
        return Pattern.compile(regex);
    }

    private boolean matchesAnyPattern(String ip) {
        Set<Pattern> allowedIpPatterns;

        if (allowedIps != null && allowedIps.length > 0) {
            allowedIpPatterns = new HashSet<>();
            for (String str : allowedIps) {
                allowedIpPatterns.add(convertToPattern(str));
            }
            System.out.println("Initialized allowed IP patterns: " + allowedIpPatterns);
        } else {
            System.err.println("No allowed IPs configured.");
            allowedIpPatterns = new HashSet<>();
        }

        for (Pattern pattern : allowedIpPatterns) {
            if (pattern.matcher(ip).matches()) {
                return true;
            }
        }
        return false;
    }
}
